<template>
  <image :src="imageUrl" :style="[imageStyle]" :mode="mode" />
</template>

<script>

export default {
  props: {
    src: String,
    mode: {
      type: String,
      default: 'widthFix'
    },
    width: {
      type: [String, Number],
      default: ''
    },
    height: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    if (this.src == null) return;
    return {
      imageUrl: '/static/images/' + this.src + '.png',
    }
  },
  computed: {
    imageStyle() {
      let style = {};
      // 通过调用addUnit()方法，如果有单位，如百分比，px单位等，直接返回，如果是纯粹的数值，则加上rpx单位
      style.width = this.addUnit(this.width);
      style.height = this.addUnit(this.height);
      return style;
    }
  },
  methods: {
    isNumber(value) {
      return /^[\+-]?(\d+\.?\d*|\.\d+|\d\.\d+e\+\d+)$/.test(value)
    },
    addUnit(value = 'auto', unit = 'rpx') {
      value = String(value);
      return this.isNumber(value) ? `${value}${unit}` : value;
    }
  }
}
</script>
